<?php

declare(strict_types=1);

namespace sheep\library\install\provider;

use sheep\library\install\InstallManager;
use think\console\Output;
use sheep\traits\ConfigSet;

class View
{
    use ConfigSet;

    protected $install = null;

    protected $output = null;

    public function __construct(InstallManager $install = null, Output $output = null)
    {
        $this->install = $install;
        $this->output = $output;
    }


    /**
     * 检测环境输出
     */
    public function envOutput($checkItem)
    {
        return $checkItem;
    }


    /**
     * 根据请求参数，设置数据库配置
     */
    public function setDatabaseConfig()
    {
        // 是否是安装
        $is_install = request()->param('is_install', 0);
        $database = request()->only([
            'mysql_hostname' => 'localhost',
            'mysql_database' => 'sheep',
            'mysql_username' => 'root',
            'mysql_password' => '',
            'mysql_hostport' => 3306,
            'mysql_prefix' => 'sa_'
        ]);

        foreach ($database as $key => $value) {
            $config_key = substr($key, ((strpos($key, '_') + 1)));
            if ($is_install) {
                // 更新 env 配置值
                $this->install->setEnvVar('DATABASE.' . strtoupper($config_key), $value);
            }

            // 更新配置值
            $this->install->setConfig('database.connections.mysql.' . $config_key, $value);
        }
    }


    /**
     * 根据请求参数，设置 redis 配置
     */
    public function setRedisConfig()
    {
        // 是否是安装
        $is_install = request()->param('is_install', 0);
        $redis = request()->only([
            'redis_host' => 'localhost',
            'redis_port' => 6379,
            'redis_password' => '',
            'redis_select' => 1,
        ]);

        foreach ($redis as $key => $value) {
            $config_key = substr($key, ((strpos($key, '_') + 1)));
            if ($is_install) {
                // 更新 env 配置值
                $this->install->setEnvVar('REDIS.' . strtoupper($key), $value);
            }

            // 更新配置值
            $this->install->setConfig('redis.' . str_replace('redis_', '', $key), $value);
        }

        // 更新配置值
        $this->coverRedisConfig();
    }

}
